package com.example.newland.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.Random;


public class ChartView extends View {
    private static final String TAG = "ChartView";
    private Paint paint;
    // 刻度之间的距离
    private int degreeSpaceW;
    private int degreeSpaceH;
    //分割粒度
    private int degreeWithNum=15;
    private int degreeHightNum=10;
    // 模拟数据.
    private ArrayList<Float> temp;
    private ArrayList<Float> hum;
    // 当前显示的数据数量
    private int showNum=degreeWithNum;


    public ChartView(Context context) {
        super(context);
        initWork();
    }

    public ChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initWork();
    }

    public ChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initWork();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

    /**
     *  初始化工作
     */
    private void initWork() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        temp= new ArrayList<>();
        hum= new ArrayList<>();

        initData();

        // 开启线程，没隔0.5秒showNum加一
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){

                    float t= (float) (  (Math.random()*100) %100  );
                    float m= (float) (  (Math.random()*100) %100  );
                    addData(t,m);

                    // 重绘
                    postInvalidate();
                    // 休眠0.5秒
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void initData() {
        for(int i=0;i<15;i++){
            float t= (float) (  (Math.random()*100) %100  );
            float m= (float) (  (Math.random()*100) %100  );
            this.addData(t,m);
        }

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawColor(Color.LTGRAY);
        TextDraw(canvas);
        AutoDraw(canvas);
    }

    private void TextDraw(Canvas canvas) {

        // 颜色设为黑色
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(26);
        paint.setPathEffect(null);

        canvas.drawText(  "温度 ", getRight()-200, getTop()+35, paint);
        canvas.drawText(  "湿度 ", getRight()-200, getTop()+70, paint);

        // 曲线颜色
        Path pivotPath = new Path();
        // 宽度为3像素
        paint.setStrokeWidth(3);
        // 画笔设置样式为STROKE样式，即只划线不填充
        paint.setStyle(Paint.Style.STROKE);

        // 颜色设为红色
        paint.setColor(Color.RED);
        pivotPath.moveTo(getRight()-200+60, getTop()+30);
        pivotPath.lineTo(getRight()-200+160, getTop()+30);
        canvas.drawPath(pivotPath, paint);

        Path pivotPath2 = new Path();
        // 颜色设为蓝色
        paint.setColor(Color.BLUE);
        pivotPath2.moveTo(getRight()-200+60, getTop()+65);
        pivotPath2.lineTo(getRight()-200+160, getTop()+65);
        canvas.drawPath(pivotPath2, paint);
    }


    private void AutoDraw(Canvas canvas) {
        // 控件上下左右边界四至及控件的宽度(同时也是高度!)
        int left = getLeft();
        int right = getRight();
        int top = getTop();
        int bottom = getBottom();

        // 图表距离控件边缘的距离
        int graphPadding = 100;
        // 图表上下左右四至
        int graphLeft = left + graphPadding;
        int graphBottom = bottom - graphPadding;
        int graphRight = right - graphPadding;
        int graphTop = top + graphPadding;
        // 图表宽度(也等同高度奥~)
        int graphW = graphRight - graphLeft;
        int graphH = graphBottom - graphTop;
        // 刻度之间的距离
        degreeSpaceW = graphW / degreeWithNum;
        degreeSpaceH = graphH / degreeHightNum;

        // 颜色设为黑色
        paint.setColor(Color.BLACK);
        // 宽度为3像素
        paint.setStrokeWidth(3);
        // 画笔设置样式为STROKE样式，即只划线不填充
        paint.setStyle(Paint.Style.STROKE);

        // 坐标系绘制
        Path pivotPath = new Path();
        //Y轴
        pivotPath.moveTo(graphLeft, graphBottom);
        pivotPath.lineTo(graphLeft, graphTop);
        //Y轴箭头
        pivotPath.lineTo(graphLeft - 12, graphTop + 20);
        pivotPath.moveTo(graphLeft, graphTop);
        pivotPath.lineTo(graphLeft + 12, graphTop + 20);
        //X轴
        pivotPath.moveTo(graphLeft, graphBottom);
        pivotPath.lineTo(graphRight, graphBottom);
        //X轴箭头
        pivotPath.lineTo(graphRight - 20, graphBottom + 12);
        pivotPath.moveTo(graphRight, graphBottom);
        pivotPath.lineTo(graphRight - 20, graphBottom - 12);
        canvas.drawPath(pivotPath, paint);


        // Y轴刻度虚线
        for (int i = 1; i < degreeHightNum; i++) {
            Path yKeduPath = new Path();
            // 线
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(1);
            paint.setStyle(Paint.Style.STROKE);
            paint.setPathEffect(new DashPathEffect(new float[]{5,5},0));
            yKeduPath.moveTo(graphLeft, graphBottom - i * degreeSpaceH);
            yKeduPath.lineTo(graphRight, graphBottom - i * degreeSpaceH);
            canvas.drawPath(yKeduPath, paint);
            // 数字
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(25);
            paint.setPathEffect(null);
            canvas.drawText(i*10 + "", graphPadding / 2, graphBottom - i * degreeSpaceH, paint);
        }
        // X轴刻度虚线
        for (int i = 1; i < degreeWithNum; i++) {

            Path xKeduPath = new Path();
            // 线
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(1);
            paint.setPathEffect(new DashPathEffect(new float[]{5,5},0));
            xKeduPath.moveTo(graphLeft + i * degreeSpaceW, graphBottom);
            xKeduPath.lineTo(graphLeft + i * degreeSpaceW, graphTop);
            canvas.drawPath(xKeduPath, paint);
            // 数字
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(25);
            paint.setPathEffect(null);


            canvas.drawText(i+"", graphLeft-30 + i * degreeSpaceW, graphBottom + graphPadding / 2, paint);

        }


        // 折线
        Path linePath = new Path();
        for (int i = 0; i < showNum; i++) {
           if(i>=temp.size()){     //防止下标超出
                break;
            }

            int toPointX = graphLeft + i * degreeSpaceW;
            int toPointY = graphBottom - ((int) (temp.get(i)/10 * degreeSpaceH));


            //记录运行路径
            if (i==0){
                linePath.moveTo(toPointX,toPointY);
            }else {
                linePath.lineTo(toPointX, toPointY);
            }

            // 节点圆圈（外圈）
            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.STROKE);
            canvas.drawCircle(toPointX, toPointY,10,paint);
            // 节点圆圈（内圈）
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(toPointX,toPointY,7,paint);
        }

        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        canvas.drawPath(linePath, paint); //将图画显示在画布当中


        // 折线2
        Path linePath2 = new Path();
        for (int i = 0; i < showNum; i++) {
            if(i>=hum.size()){     //防止下标超出
                break;
            }

            int toPointX = graphLeft + i * degreeSpaceW;
            int toPointY = graphBottom - ((int) (hum.get(i)/10 * degreeSpaceH));


            //记录运行路径
            if (i==0){
                linePath2.moveTo(toPointX,toPointY);
            }else {
                linePath2.lineTo(toPointX, toPointY);
            }

            // 节点圆圈（外圈）
            paint.setColor(Color.BLUE);
            paint.setStyle(Paint.Style.STROKE);
            canvas.drawCircle(toPointX, toPointY,10,paint);
            // 节点圆圈（内圈）
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(toPointX,toPointY,7,paint);
        }

        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        canvas.drawPath(linePath2, paint); //将图画显示在画布当中
    }

    public void addTempData(double v) {
        temp.add((float) v);
        if(temp.size()>degreeWithNum)
            temp.remove(0);
        postInvalidate();
    }

    public void addHumData(double v) {
        hum.add((float) v);
        if(hum.size()>degreeWithNum)
            hum.remove(0);
        postInvalidate();
    }

    public void addData(double v, double v1) {
        temp.add((float) v);
        hum.add((float) v1);

        if(temp.size()>degreeWithNum)
            temp.remove(0);
        if(hum.size()>degreeWithNum)
            hum.remove(0);

        postInvalidate();
    }
}
